package com.example.dw.admin.service.impl;

import com.example.dw.admin.dto.PageRequestDTO;
import com.example.dw.admin.dto.CreateUserDTO;
import com.example.dw.admin.dto.UpdateUserDTO;
import com.example.dw.admin.service.AdminUserService;
import com.example.dw.entity.User;
import com.example.dw.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理端用户管理服务实现类
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, Object> getUserByPage(PageRequestDTO pageRequest) {
        Page<User> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(pageRequest.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                .like("username", pageRequest.getKeyword())
                .or().like("nickname", pageRequest.getKeyword())
                .or().like("realname", pageRequest.getKeyword())
                .or().like("phone", pageRequest.getKeyword())
            );
        }
        
        // 排序
        if (StringUtils.hasText(pageRequest.getSortBy())) {
            if ("desc".equalsIgnoreCase(pageRequest.getSortOrder())) {
                queryWrapper.orderByDesc(pageRequest.getSortBy());
            } else {
                queryWrapper.orderByAsc(pageRequest.getSortBy());
            }
        } else {
            queryWrapper.orderByDesc("create_time");
        }
        
        IPage<User> result = userMapper.selectPage(page, queryWrapper);
        
        Map<String, Object> response = new HashMap<>();
        response.put("list", result.getRecords());
        response.put("total", result.getTotal());
        response.put("page", result.getCurrent());
        response.put("size", result.getSize());
        
        return response;
    }

    @Override
    public User getUserById(Integer userid) {
        return userMapper.selectById(userid);
    }

    @Override
    public void createUser(CreateUserDTO createUserDTO) {
        // 检查用户名是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", createUserDTO.getUsername());
        
        if (userMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("用户名已存在");
        }
        
        User user = new User();
        BeanUtils.copyProperties(createUserDTO, user);
        user.setPassword(passwordEncoder.encode(createUserDTO.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        user.setStatus(0); // 0-正常状态
        
        userMapper.insert(user);
    }

    @Override
    public void updateUser(UpdateUserDTO updateUserDTO) {
        User existingUser = userMapper.selectById(updateUserDTO.getUserid());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 如果更新用户名，检查是否重复
        if (StringUtils.hasText(updateUserDTO.getUsername()) && 
            !updateUserDTO.getUsername().equals(existingUser.getUsername())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", updateUserDTO.getUsername())
                       .ne("userid", updateUserDTO.getUserid());
            
            if (userMapper.selectCount(queryWrapper) > 0) {
                throw new RuntimeException("用户名已存在");
            }
        }
        
        User user = new User();
        BeanUtils.copyProperties(updateUserDTO, user);
        user.setUpdateTime(LocalDateTime.now());
        
        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(Integer userid) {
        User user = userMapper.selectById(userid);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        userMapper.deleteById(userid);
    }

    @Override
    public List<User> getAllUser(Integer role) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        if (role != null) {
            queryWrapper.eq("role", role);
        }
        
        queryWrapper.eq("enabled", 1);
        queryWrapper.orderByDesc("create_time");
        
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public Map<String, Object> getTeacherByPage(PageRequestDTO pageRequest) {
        Page<User> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role", 1); // 教师角色
        
        // 关键词搜索
        if (StringUtils.hasText(pageRequest.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                .like("username", pageRequest.getKeyword())
                .or().like("nickname", pageRequest.getKeyword())
                .or().like("realname", pageRequest.getKeyword())
            );
        }
        
        queryWrapper.orderByDesc("create_time");
        IPage<User> result = userMapper.selectPage(page, queryWrapper);
        
        Map<String, Object> response = new HashMap<>();
        response.put("list", result.getRecords());
        response.put("total", result.getTotal());
        response.put("page", result.getCurrent());
        response.put("size", result.getSize());
        
        return response;
    }

    @Override
    public User getTeacherById(Integer userid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", userid).eq("role", 1);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<String, Object> getStudentByPage(PageRequestDTO pageRequest) {
        Page<User> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role", 0); // 学生角色
        
        // 关键词搜索
        if (StringUtils.hasText(pageRequest.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                .like("username", pageRequest.getKeyword())
                .or().like("nickname", pageRequest.getKeyword())
                .or().like("realname", pageRequest.getKeyword())
            );
        }
        
        queryWrapper.orderByDesc("create_time");
        IPage<User> result = userMapper.selectPage(page, queryWrapper);
        
        Map<String, Object> response = new HashMap<>();
        response.put("list", result.getRecords());
        response.put("total", result.getTotal());
        response.put("page", result.getCurrent());
        response.put("size", result.getSize());
        
        return response;
    }

    @Override
    public User getStudentById(Integer userid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", userid).eq("role", 0);
        return userMapper.selectOne(queryWrapper);
    }
} 